<?php

namespace mpend\controllers;

use Yii;
use mpend\components\Controller;
use yii\web\UploadedFile;
use common\helpers\Utils;
use mpend\models\UploadImage;
use mpend\models\UploadVideo;
use mpend\models\UploadAttach;

/**
 * 附件上传
 *
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class AttachsController extends Controller {

    /**
     * @inheritdoc
     */
    protected function verbs() {
        return [
            '*' => ['POST'],
        ];
    }

    /**
     * @inheritdoc
     */
    protected function rules() {
        return [
            [
                'allow' => true,
                'roles' => ['@'],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    protected $remotePath = null;

    /**
     * 附件上传
     */
    public function actionUpload() {
        $model = new UploadAttach();
        $params = Yii::$app->request->post();
        $params['streamFile'] = UploadedFile::getInstanceByName('streamFile');
        $params['user_id'] = $this->uid;
        if (!$model->load($params, '')) {
            parent::warning('上传提交时数据未加载成功！');
        }
        return $model->upload();
    }

    /**
     * 附件上传
     */
    public function actionUploadImage() {
        $model = new UploadImage();
        $params = Yii::$app->request->post();
        $params['imageFile'] = UploadedFile::getInstanceByName('imageFile');
        $params['user_id'] = $this->uid;
        Yii::error($params);
        if (!$model->load($params, '')) {
            parent::warning('上传提交时数据未加载成功！');
        }
        return $model->upload();
    }

    /**
     * 附件上传
     */
    public function actionUploadVideo() {
        $model = new UploadVideo();
        $params = Yii::$app->request->post();
        $params['videoFile'] = UploadedFile::getInstanceByName('videoFile');
        $params['user_id'] = $this->uid;
        if (!$model->load($params, '')) {
            parent::warning('上传提交时数据未加载成功！');
        }
        return $model->upload();
    }

    /**
     * 阿里STS授权
     */
    public function actionAuthent() {
        /* @var $sts \common\components\aliyun\AliyunSTS */
        $sts = Yii::$app->alists;
        $data = $sts->authent();
        $data['bucket'] = $sts->bucket;
        $data['endpoint'] = $sts->endpoint;
        return $data;
    }

    public function afterAction($action, $result) {
        if ($this->remotePath != null) {
            Utils::pushCDN($this->remotePath);
        }
        return parent::afterAction($action, $result);
    }

}
